package com.cltech.service.sys.impl;

import com.cltech.dto.SysDicItemDto;
import com.cltech.entity.sys.SysDic;
import com.cltech.entity.sys.SysDicItem;
import com.cltech.frame.base.impl.BaseServiceImpl;
import com.cltech.frame.result.ResponseBean;
import com.cltech.frame.specification.utils.SpecificationSortUtil;
import com.cltech.mapper.SysDicItemMapper;
import com.cltech.repository.sys.SysDicItemRepository;
import com.cltech.service.sys.SysDicItemService;
import com.cltech.service.sys.SysDicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Map;

@Service
@Transactional
public class SysDicItemServiceImpl extends BaseServiceImpl<SysDicItem, String> implements SysDicItemService {
    private SysDicItemRepository sysDicItemRepository;
    @Autowired
    private SysDicService sysDicService;
    @Autowired
    private SysDicItemMapper sysDicItemMapper;

    @Autowired
    public void setSysUserRepository(SysDicItemRepository sysDicItemRepository) {
        this.sysDicItemRepository = sysDicItemRepository;
        super.setBaseRepository(sysDicItemRepository);
    }

    @Override
    public Page<SysDicItemDto> findAll(Map<String, String[]> queryParameters, int pageNo, int pageSize) {
        Map<String, Object> map = SpecificationSortUtil.creat(queryParameters, SysDicItem.class);
        Specification<SysDicItem> specification = (Specification<SysDicItem>) map.get(SpecificationSortUtil.SEARCHS);
        Sort sort = (Sort) map.get(SpecificationSortUtil.ORDERS);
        Pageable page = null == sort ? new PageRequest(0, 15) : new PageRequest(0, 15, sort);
        if (null == specification) {
            return sysDicItemMapper.entityToDto(sysDicItemRepository.findAll(page));
        } else {
            return sysDicItemMapper.entityToDto(sysDicItemRepository.findAll(specification,
                    page));
        }
    }

    @Override
    public ResponseBean<SysDicItem> addOrUpdate(SysDicItemDto dto) {
        SysDicItem entity = sysDicItemMapper.dtoToEntity(dto);
        if (!StringUtils.isEmpty(dto.getDicId())) {
            SysDic sysDic = sysDicService.findById(dto.getDicId()).getData().orElse(null);
            if (null == sysDic) {
                return ResponseBean.fail("字典不存在");
            }
            entity.setDic(sysDic);
        }
        return save(entity);
    }
}
